// Elements
const sendBtn = document.getElementById("send-btn");
const userInput = document.getElementById("user-input");
const chatDisplay = document.getElementById("chat-display");

// Function to add messages to the chat display
function addMessage(message, sender) {
  const messageElement = document.createElement("div");
  messageElement.classList.add("message", sender === "user" ? "user-message" : "server-message");
  messageElement.innerText = message;
  chatDisplay.appendChild(messageElement);
  chatDisplay.scrollTop = chatDisplay.scrollHeight; // Auto-scroll to bottom
}

// Function to handle message sending
function sendMessage() {
  const userMessage = userInput.value.trim();
  if (userMessage) {
    // Display user's message
    addMessage(userMessage, "user");
    userInput.value = ""; // Clear input field

    // Send the message to the server and get the response
    fetchServerResponse(userMessage);
  }
}

// Function to communicate with the server
function fetchServerResponse(userMessage) {
  fetch("http://localhost:5000/AIChat", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ query: userMessage }),
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error("Server error");
      }
      return response.json();
    })
    .then((data) => {
      if (data.response) {
        addMessage(data.response, "server");
      } else {
        addMessage("服务器没有返回内容。", "server");
      }
    })
    .catch((error) => {
      console.error("Error:", error);
      addMessage("无法连接到服务器。请稍后再试。", "server");
    });
}

// Event Listeners
sendBtn.addEventListener("click", sendMessage);
userInput.addEventListener("keypress", (e) => {
  if (e.key === "Enter") sendMessage();
});
function goBack() {
  // 检查浏览器历史是否可以返回
  if (window.history.length > 1) {
    window.history.back(); // 返回上一页
  } else {
    // 如果没有历史记录，返回到指定的主页或默认页面
    window.location.href = '../../../afterLogin/src/home.html'; // 可以替换为您期望的默认页面 URL
  }
}
